package com.cyl.manager.vip.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.cyl.h5.domain.dto.PayNotifyMessageDTO;
import com.cyl.h5.domain.form.VipPayForm;
import com.cyl.h5.domain.vo.VipPayVO;
import com.cyl.manager.act.domain.entity.FhRechargeData;
import com.cyl.manager.act.domain.vo.H5FhInfoUser;
import com.cyl.manager.act.mapper.H5FhInfoUserMapper;
import com.cyl.manager.act.service.FhRechargeDataService;
import com.cyl.wechat.WechatPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cyl.manager.vip.mapper.VipOrderMapper;
import com.cyl.manager.vip.domain.entity.VipOrder;
import com.cyl.manager.vip.domain.entity.VipAutoRenew;
import com.cyl.manager.vip.service.IVipOrderService;
import com.cyl.manager.vip.service.IVipAutoRenewService;

/**
 * VIP订单Service业务层处理
 *
 * @author system
 */
@Service
public class VipOrderServiceImpl implements IVipOrderService {
    private static final Logger log = LoggerFactory.getLogger(VipOrderServiceImpl.class);

    @Autowired
    private VipOrderMapper vipOrderMapper;

    @Autowired
    private FhRechargeDataService fhRechargeDataService;

    @Autowired
    private H5FhInfoUserMapper fhInfoUserMapper;

    @Autowired
    private WechatPayService wechatPayService;

    @Autowired
    private IVipAutoRenewService vipAutoRenewService;

    /**
     * 查询VIP订单
     *
     * @param id VIP订单主键
     * @return VIP订单
     */
    @Override
    public VipOrder selectVipOrderById(Long id) {
        return vipOrderMapper.selectVipOrderById(id);
    }

    /**
     * 查询VIP订单列表
     *
     * @param vipOrder VIP订单
     * @return VIP订单
     */
    @Override
    public List<VipOrder> selectVipOrderList(VipOrder vipOrder) {
        return vipOrderMapper.selectVipOrderList(vipOrder);
    }

    /**
     * 新增VIP订单
     *
     * @param vipOrder VIP订单
     * @return 结果
     */
    @Override
    public int insertVipOrder(VipOrder vipOrder) {
        vipOrder.setCreateTime(LocalDateTime.now());
        return vipOrderMapper.insertVipOrder(vipOrder);
    }

    /**
     * 修改VIP订单
     *
     * @param vipOrder VIP订单
     * @return 结果
     */
    @Override
    public int updateVipOrder(VipOrder vipOrder) {
        vipOrder.setUpdateTime(LocalDateTime.now());
        return vipOrderMapper.updateVipOrder(vipOrder);
    }

    /**
     * 批量删除VIP订单
     *
     * @param ids 需要删除的VIP订单主键
     * @return 结果
     */
    @Override
    public int deleteVipOrderByIds(Long[] ids) {
        return vipOrderMapper.deleteVipOrderByIds(ids);
    }

    /**
     * 删除VIP订单信息
     *
     * @param id VIP订单主键
     * @return 结果
     */
    @Override
    public int deleteVipOrderById(Long id) {
        return vipOrderMapper.deleteVipOrderById(id);
    }

    /**
     * 根据订单号查询VIP订单
     *
     * @param orderSn 订单号
     * @return VIP订单
     */
    @Override
    public VipOrder selectVipOrderByOrderSn(String orderSn) {
        return vipOrderMapper.selectVipOrderByOrderSn(orderSn);
    }

    /**
     * 根据用户ID查询VIP订单列表
     *
     * @param userId 用户ID
     * @return VIP订单集合
     */
    @Override
    public List<VipOrder> selectVipOrderListByUserId(Long userId) {
        return vipOrderMapper.selectVipOrderListByUserId(userId);
    }

    /**
     * 创建VIP订单
     *
     * @param userId 用户ID
     * @param rechargeDataId VIP配置ID
     * @param vipDays VIP天数
     * @param amount 订单金额
     * @param payAmount 实付金额
     * @param payType 支付方式
     * @param isAutoRenew 是否自动续费
     * @return VIP订单
     */
    @Override
    @Transactional
    public VipOrder createVipOrder(Long userId, Long rechargeDataId, Integer vipDays,
                                   BigDecimal amount, BigDecimal payAmount, Integer payType, Boolean isAutoRenew)
    {
        VipOrder vipOrder = new VipOrder();
        vipOrder.setOrderSn(generateOrderSn());
        vipOrder.setUserId(userId);
        vipOrder.setRechargeDataId(rechargeDataId);
        vipOrder.setVipDays(vipDays);
        vipOrder.setAmount(amount);
        vipOrder.setPayAmount(payAmount);
        vipOrder.setPayType(payType);
        vipOrder.setIsAutoRenew(isAutoRenew); // 设置自动续费标识
        vipOrder.setStatus(0); // 待支付
        vipOrder.setDelFlag("0");
        vipOrder.setCreateTime(LocalDateTime.now());

        vipOrderMapper.insertVipOrder(vipOrder);
        return vipOrder;
    }

    /**
     * 生成订单号
     *
     * @return 订单号
     */
    private String generateOrderSn() {
        return "VIP" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 支付成功回调处理
     *
     * @param messageDTO 支付回调消息对象
     * @return 结果
     */
    @Override
    @Transactional
    public boolean paySuccessCallback(PayNotifyMessageDTO messageDTO) {
        log.info("VIP订单支付成功回调开始，支付消息：{}", messageDTO);

        try {
            // 从PayNotifyMessageDTO中提取订单号
            String orderSn = String.valueOf(messageDTO.getStringoutTradeNo());
            String thirdPartyOrderSn = messageDTO.getTradeNo();

            log.info("处理VIP订单支付回调，订单号：{}，第三方订单号：{}，交易状态：{}",
                       orderSn, thirdPartyOrderSn, messageDTO.getTradeStatus());

            // 检查交易状态是否为成功
            if (!"SUCCESS".equals(messageDTO.getTradeStatus())) {
                log.warn("交易状态不是成功状态，跳过处理，订单号：{}，状态：{}", orderSn, messageDTO.getTradeStatus());
                return false;
            }

            // 根据订单号查询订单
            VipOrder vipOrder = vipOrderMapper.selectVipOrderByOrderSn(orderSn);
            if (vipOrder == null) {
                log.error("VIP订单不存在，订单号：{}", orderSn);
                return false;
            }

            // 检查订单状态
            if (vipOrder.getStatus() == 1) {
                log.info("VIP订单已支付，无需重复处理，订单号：{}", orderSn);
                return true;
            }

            // 更新订单状态为已支付
            vipOrder.setStatus(1);
            vipOrder.setThirdPartyOrderSn(thirdPartyOrderSn);
            // 将Date转换为LocalDateTime
            if (messageDTO.getPayTime() != null) {
                vipOrder.setPayTime(messageDTO.getPayTime().toInstant()
                    .atZone(java.time.ZoneId.systemDefault()).toLocalDateTime());
            } else {
                vipOrder.setPayTime(LocalDateTime.now());
            }
            vipOrder.setUpdateTime(LocalDateTime.now());
            vipOrderMapper.updateVipOrder(vipOrder);

            // 更新用户VIP信息
            updateUserVipInfo(vipOrder);

            // 处理自动续费逻辑
            if (vipOrder.getIsAutoRenew() != null && vipOrder.getIsAutoRenew()) {
                handleAutoRenewSubscription(vipOrder);
            }

            log.info("VIP订单支付成功回调处理完成，订单号：{}", orderSn);
            return true;
        } catch (Exception e) {
            log.error("VIP订单支付成功回调处理失败，支付消息：{}，错误信息：{}", messageDTO, e.getMessage(), e);
            throw new RuntimeException("VIP订单支付回调处理失败", e);
        }
    }

    /**
     * 更新用户VIP信息
     *
     * @param vipOrder VIP订单
     */
    private void updateUserVipInfo(VipOrder vipOrder) {
        try {
            // 查询用户信息
            H5FhInfoUser user = fhInfoUserMapper.selectFhInfoUserByUserId(vipOrder.getUserId());
            if (user == null) {
                log.error("用户不存在，用户ID：{}", vipOrder.getUserId());
                return;
            }

            // 从VipOrder中获取VIP天数，不需要查询充值数据
            Integer vipDays = vipOrder.getVipDays();
            if (vipDays == null || vipDays <= 0) {
                log.error("VIP天数无效，订单ID：{}，VIP天数：{}", vipOrder.getId(), vipDays);
                return;
            }

            // 记录原始状态用于日志
            Integer originalIsVip = user.getIsVip();
            Integer originalVipDays = user.getVipDays();
            LocalDateTime originalExpireTime = user.getVipExpireTime();

            user.setIsVip(1); // 设置为VIP

            // 累加VIP天数
            Integer currentVipDays = user.getVipDays() != null ? user.getVipDays() : 0;
            user.setVipDays(currentVipDays + vipDays);

            // 计算VIP到期时间 - 在原有基础上累加
            LocalDateTime expireTime;
            LocalDateTime now = LocalDateTime.now();

            if (user.getVipExpireTime() != null && user.getVipExpireTime().isAfter(now)) {
                // 如果用户当前VIP未过期，在原有到期时间基础上延长
                expireTime = user.getVipExpireTime().plusDays(vipDays);
            } else {
                // 如果用户VIP已过期或没有VIP，从当前时间开始计算
                expireTime = now.plusDays(vipDays);
            }

            user.setVipExpireTime(expireTime);
            user.setUpdateTime(LocalDateTime.now());

            // 执行更新操作，带重试机制
            int maxRetries = 3;
            for (int i = 0; i < maxRetries; i++) {
                try {
                    int updateResult = fhInfoUserMapper.updateFhInfoUser(user);
                    if (updateResult > 0) {
                        log.info("用户VIP信息更新成功，用户ID：{}，VIP状态: {} -> {}, VIP天数: {} -> {}, 到期时间: {} -> {}",
                                   user.getId(), originalIsVip, user.getIsVip(),
                                   originalVipDays, user.getVipDays(),
                                   originalExpireTime, user.getVipExpireTime());
                        break;
                    } else {
                        log.warn("用户VIP信息更新失败，用户ID：{}，重试次数：{}", user.getId(), i + 1);
                        if (i == maxRetries - 1) {
                            throw new RuntimeException("用户VIP信息更新失败，已达到最大重试次数");
                        }
                    }
                } catch (Exception e) {
                    log.error("用户VIP信息更新异常，用户ID：{}，重试次数：{}，错误：{}",
                               user.getId(), i + 1, e.getMessage());
                    if (i == maxRetries - 1) {
                        throw e;
                    }
                    // 等待一段时间后重试
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException("线程被中断", ie);
                    }
                }
            }
        } catch (Exception e) {
            log.error("更新用户VIP信息失败，订单ID：{}，用户ID：{}，错误信息：{}",
                        vipOrder.getId(), vipOrder.getUserId(), e.getMessage(), e);
            throw new RuntimeException("更新用户VIP信息失败", e);
        }
    }

    /**
     * 取消订单
     *
     * @param orderSn 订单号
     * @return 结果
     */
    @Override
    @Transactional
    public boolean cancelOrder(String orderSn) {
        try {
            VipOrder vipOrder = vipOrderMapper.selectVipOrderByOrderSn(orderSn);
            if (vipOrder == null || vipOrder.getStatus() != 0) {
                return false; // 订单不存在或不是待支付状态
            }
            vipOrder.setStatus(2); // 已取消
            vipOrder.setUpdateTime(LocalDateTime.now());
            vipOrderMapper.updateVipOrder(vipOrder);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * VIP订单支付
     *
     * @param vipPayForm 支付表单
     * @return 支付结果
     */
    @Override
    @Transactional
    public VipPayVO vipOrderPay(VipPayForm vipPayForm) {
        try {
            // 1. 查询待支付的VIP订单
            VipOrder vipOrder = vipOrderMapper.selectVipOrderByOrderSn(vipPayForm.getOrderSn());
            if (vipOrder == null) {
                throw new RuntimeException("VIP订单不存在");
            }
            if (vipOrder.getStatus() != 0) {
                throw new RuntimeException("订单状态异常，无法支付");
            }

            // 2. 查询VIP配置信息
             FhRechargeData rechargeData = fhRechargeDataService.selectById(vipOrder.getRechargeDataId());
            if (rechargeData == null) {
                throw new RuntimeException("VIP配置不存在");
            }

            // 3. 构建订单描述
            String orderDesc = "VIP会员-" + rechargeData.getDay() + "天";
            if (orderDesc.length() > 40) {
                orderDesc = orderDesc.substring(0, 40);
            }

            // 4. 调用微信支付
            Map<String, String> payParams = wechatPayService.appPay(
                    vipOrder.getOrderSn(),
                    orderDesc,
                    vipOrder.getPayAmount().multiply(new BigDecimal(100)).intValue(), // 转换为分
                    vipPayForm.getUserId(),
                    "1212112",
                    "https://www.bjshangyu.cn/appApi/no-auth/wechat/vip/notify"
            );

            // 5. 构建返回结果
            VipPayVO response = new VipPayVO();
            response.setPayType(vipOrder.getPayType());
            response.setAppId(payParams.get("appid"));
            response.setPartnerId(payParams.get("partnerid"));
            response.setPrepayId(payParams.get("prepayid"));
            response.setPackage_(payParams.get("package"));
            response.setNonceStr(payParams.get("noncestr"));
            response.setTimeStamp(payParams.get("timestamp"));
            response.setSign(payParams.get("sign"));

            return response;
        } catch (Exception e) {
            throw new RuntimeException("VIP支付调用失败: " + e.getMessage(), e);
        }
    }

    /**
     * 处理自动续费订阅
     *
     * @param vipOrder VIP订单
     */
    private void handleAutoRenewSubscription(VipOrder vipOrder) {
        try {
            log.info("开始处理自动续费订阅，订单号：{}，用户ID：{}", vipOrder.getOrderSn(), vipOrder.getUserId());

            // 1. 检查支付方式是否支持自动续费（目前只支持微信支付）
            if (vipOrder.getPayType() == null || vipOrder.getPayType() != 2) {
                log.warn("当前支付方式不支持自动续费，订单号：{}，支付方式：{}", vipOrder.getOrderSn(), vipOrder.getPayType());
                return;
            }

            // 2. 查询VIP配置信息
            FhRechargeData rechargeData = fhRechargeDataService.selectById(vipOrder.getRechargeDataId());
            if (rechargeData == null) {
                log.error("VIP配置不存在，无法设置自动续费，配置ID：{}", vipOrder.getRechargeDataId());
                return;
            }

            // 3. 计算下次续费时间（VIP到期前3天）
            H5FhInfoUser user = fhInfoUserMapper.selectFhInfoUserByUserId(vipOrder.getUserId());
            if (user == null || user.getVipExpireTime() == null) {
                log.error("用户信息或VIP到期时间不存在，无法设置自动续费，用户ID：{}", vipOrder.getUserId());
                return;
            }

            LocalDateTime nextRenewTime = user.getVipExpireTime().minusDays(3);

            // 4. 检查是否已存在自动续费记录
            VipAutoRenew existingAutoRenew = vipAutoRenewService.selectVipAutoRenewByUserIdAndRechargeDataId(
                vipOrder.getUserId(), vipOrder.getRechargeDataId());

            if (existingAutoRenew != null) {
                log.info("用户已存在自动续费记录，更新记录，用户ID：{}，记录ID：{}", vipOrder.getUserId(), existingAutoRenew.getId());
                
                // 更新现有记录，但不在回调中进行签约
                existingAutoRenew.setOriginalOrderSn(vipOrder.getOrderSn());
                existingAutoRenew.setNextRenewTime(nextRenewTime);
                existingAutoRenew.setStatus(1); // 激活状态，但需要用户主动完成签约
                existingAutoRenew.setRetryCount(0);
                existingAutoRenew.setFailureReason(null);
                vipAutoRenewService.updateVipAutoRenew(existingAutoRenew);
            } else {
                // 5. 创建自动续费记录（待签约状态）
                VipAutoRenew vipAutoRenew = new VipAutoRenew();
                vipAutoRenew.setUserId(vipOrder.getUserId());
                vipAutoRenew.setRechargeDataId(vipOrder.getRechargeDataId());
                vipAutoRenew.setOriginalOrderSn(vipOrder.getOrderSn());
                vipAutoRenew.setPayType(vipOrder.getPayType());
                vipAutoRenew.setAmount(vipOrder.getAmount());
                vipAutoRenew.setVipDays(vipOrder.getVipDays());
                vipAutoRenew.setNextRenewTime(nextRenewTime);
                vipAutoRenew.setStatus(1); // 1表示激活状态
                vipAutoRenew.setRetryCount(0);
                vipAutoRenew.setMaxRetryCount(3); // 最大重试3次
                vipAutoRenew.setContractStatus(null); // 待签约状态，需要用户主动完成
                vipAutoRenew.setDelFlag("0");

                vipAutoRenewService.insertVipAutoRenew(vipAutoRenew);
                log.info("自动续费记录创建成功，记录ID：{}，用户需要完成委托代扣签约", vipAutoRenew.getId());
            }

            log.info("自动续费订阅设置成功，订单号：{}，用户ID：{}，下次续费时间：{}",
                     vipOrder.getOrderSn(), vipOrder.getUserId(), nextRenewTime);

        } catch (Exception e) {
            log.error("处理自动续费订阅失败，订单号：{}，错误信息：{}", vipOrder.getOrderSn(), e.getMessage(), e);
            // 自动续费失败不影响主流程，只记录日志
        }
    }
}
